package com.chb.stack;

import com.chb.queue.MyQueue;

import java.util.Scanner;
import java.util.Stack;

/**
 * 栈 模拟
 */
public class MyStackDemo {
    public static void main(String[] args) {
        Stack<Integer> s = new Stack<Integer>();
        s.push(1);
        MyStack myStack = new MyStack(3);
        Scanner in = new Scanner(System.in);
        String key = ""; // 接受用户输入
        boolean flag = true;
        System.out.println("push: 添加元素");
        System.out.println("pop: 取出元素");
        System.out.println("show: 打印元素");
        System.out.println("exit: 退出程序");

        while(flag) {
            System.out.println("请输入选项: ");
            key = in.next();
            switch (key) {
                case "push":
                    System.out.println("请输入一个数: ");
                    int input = in.nextInt();
                    myStack.push(input);
                    break;
                case "pop":
                    myStack.pop();
                    break;
                case "show":
                    myStack.show();
                    break;
                case "exit":
                    in.close();
                    flag = false;
                    break;
                default:
                    break;
            }

        }
        System.out.println("Exit!!!");
    }
}

/**
 * 使用数据模拟栈
 */
class MyStack {
    private int capacity;
    private int[] data;
    private int top = -1; // 栈顶的位置

    public MyStack(int initCapacity) {
        this.capacity = initCapacity;
        data = new int[this.capacity];
    }

    public boolean isFull() {
        return top == capacity - 1;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    // 入栈
    public void push(int value) {
        if (isFull()) {
            System.out.println("栈满");
        } else {
            top++;
            data[top] = value;
        }
    }

    // 出栈
    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈空");
        }
        int retVal = data[top];
        top--;
        return retVal;
    }

    // 展示
    public void show() {
        if (isEmpty()) {
            System.out.println("栈空");
            return;
        }
        for (int i = 0; i <= top; i++) {
            System.out.printf("stack[%d]=%d,", i, data[i]);
        }
        System.out.println();
    }

}
